import 'dart:ui';

import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'state.dart';

// 注销账号控制器
class RemoveAccountController extends GetxController
    with CacheMixin, RealtimeInfoMixin, BluetoothMixin {
  final RemoveAccountState state = RemoveAccountState();

  // 注销账号
  logOffOnTap() {
    LxAlert.show(
      local.after_removing_the_account,
      cancelTitle: local.cancel,
      confirmTitle: local.confirm,
      contentTextAlign: TextAlign.center,
      confirmCallback: (p0) {
        Loading.showLoading(null);
        ApiHelper().removeAccount().then((success) {
          if (success) {
            return cacheMixinDeleteUser(
              GlobalService.to.cacheUserInfo.value.uid,
            ).then((_) async {
              // 停止轮询获取车辆实时数据
              return realtimeInfoMixinStopLoopToGetVehicleRealTimeData()
                  .then((success) async {
                if (success) {
                  VechileConnectionService.to.bluetoothConnectHelper!
                      .disconnect()
                      .then((_) {
                    Loading.showToast(local.remove_account_success);
                    // 注销账号
                    Get.offAllNamed(AppRoutes.LOGIN_REGISTER);
                  });
                } else {
                  Loading.showError(local.logout_failed);
                }
              });
            });
          }
          throw Exception(local.remove_account_success);
        }).catchErrorHandler();
      },
    );
  }
}
